package com.kexinde.wjifen.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.kexinde.wjifen.dao.IBaseDao;

public class BaseDao<T> implements IBaseDao<T> {

	protected HibernateTemplate hibernateTemplate;

	@Override
	public boolean doDelete(T t) {
		if (null == t) {
			return false;
		}
		hibernateTemplate.delete(t);
		return true;
	}

	@Override
	public boolean doInsert(T t) {
		if (null == t) {
			return false;
		}
		hibernateTemplate.save(t);
		return true;
	}

	@Override
	public boolean doUpdate(T t) {
		if (null == t) {
			return false;
		}
		hibernateTemplate.update(t);
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll(String tableName, Integer begin, Integer length) {
		Session session = hibernateTemplate.getSessionFactory().openSession();
		session.beginTransaction();
		Query q = session.createQuery("from " + tableName);
		if (null != begin) {
			q.setMaxResults(length);
			if (null != length) {
				q.setFirstResult(begin);
			}
		}
		List<T> ts = (List<T>) q.list();
		session.getTransaction().commit();
//		session.close();
		return ts;
	}

	@Override
	public long findLength(String tableName) {
		Session session = hibernateTemplate.getSessionFactory().openSession();
		session.beginTransaction();
		Query q = session.createQuery("select count(*) from " + tableName);
		long count = (Long) q.uniqueResult();
		session.getTransaction().commit();
//		session.close();
		return count;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

}
